<template>
  <div class="overflow-hidden">
    <n-card title="" :bordered="false" class="h-full rounded-8px shadow-sm">
      <div class="flex-col h-full">
        <n-space class="pb-12px" justify="space-between">
          <n-space>
            <n-input v-model:value="keywords" type="text" placeholder="请输入关键字" clearable />
            <n-button type="primary" @click="handleSearchldTable"> 查询 </n-button>
            <n-button type="primary" @click="handleAddTable">
              <icon-ic-round-plus class="mr-4px text-20px" />
              新增
            </n-button>
          </n-space>
          <n-space align="center" :size="18">
            <n-button size="small" type="primary" @click="getTableData()">
              <icon-mdi-refresh class="mr-4px text-16px" :class="{ 'animate-spin': loading }" />
              刷新表格
            </n-button>
            <column-setting v-model:columns="columns" />
          </n-space>
        </n-space>
        <n-data-table remote :columns="columns" :data="tableData" :loading="loading" :pagination="pagination" flex-height
          class="flex-1-hidden" />
        <table-action-modal v-model:visible="visible" @refresh="getTableData()" />
      </div>
    </n-card>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref } from "vue";
import type { Ref } from "vue";
import { NButton, NPopconfirm, NSpace, NTag } from "naive-ui";
import type { DataTableColumns, PaginationProps } from "naive-ui";
import { selectOperatorLinksList, deleteOperatorLinks } from "@/service";
import { useBoolean, useLoading } from "@/hooks";
import TableActionModal from "./components/table-action-modal.vue";
import ColumnSetting from "./components/column-setting.vue";
import { useClipboard } from '@vueuse/core';
import { useRoute, useRouter } from "vue-router";

const { copy, isSupported } = useClipboard();
const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean();
const route = useRoute();
const router = useRouter();

const columns: Ref<DataTableColumns<any>> = ref([
  {
    key: "duanju_id",
    title: "ID",
    align: "center",
  },
  {
    key: "SurfacePlot",
    title: "短剧封面",
    align: "center",
    render: (row: any) => {
      return <n-image width="50" lazy src={row.SurfacePlot} />;
    },
  },
  {
    key: "duanju_name",
    title: "短剧名称",
    align: "center",
  },
  {
    key: "episodes",
    title: "集数",
    align: "center",
  },
  {
    key: "platform",
    title: "渠道",
    align: "center",
    render: (row: any) => {
      if (row.platform == 'wx') {
        return <div>微信小程序</div>;
      } else if (row.platform == 'dy') {
        return <div>抖音小程序</div>;
      } else {
        return <div>H5</div>;
      }
    },
  },
  {
    key: "links",
    title: "推广链接",
    align: "center",
    render: (row: any) => {
      return (
        <NSpace justify={"center"}>
          <div>{row.links}</div>
          <NButton size={"small"} onClick={() => copyLink(row)}>
            复制链接
          </NButton>
        </NSpace>
      )
    }
  },
  {
    key: "actions",
    title: "操作",
    align: "center",
    render: (row: any) => {
      return (
        <NSpace justify={"center"}>
          <NButton size={"small"} onClick={() => handleEditTable(row)}>
            数据详情
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDeleteTable(row.id)}>
            {{
              default: () => "确认删除",
              trigger: () => <NButton size={"small"}>删除</NButton>,
            }}
          </NPopconfirm>
        </NSpace>
      );
    },
  },
]) as Ref<any>;

let keywords = ref('')
// 查询
function handleSearchldTable() {
  pagination.page = 1
  getTableData()
}

// 复制链接
function copyLink(row:any) {
  if (!isSupported) {
    window.$message?.error('您的浏览器不支持Clipboard API');
    return;
  }
  copy(row.links);
  window.$message?.success(`复制成功：${row.links}`);
} 

// 添加
function handleAddTable() {
  openModal();
}

// 数据详情
async function handleEditTable(row: any) {
  console.log(row);
  router.push({
		path: '/popularize/particulars',
		query: {
			duanju_id: row.duanju_id,
			duanju_name: row.duanju_name,
      platform: row.platform,
      episodes: row.episodes
		}
	})
}

// 删除
async function handleDeleteTable(rowId: string) {
  const params = {
    id: rowId
  };
  const res: any = await deleteOperatorLinks(params);
  if (res.code === 0) {
    window.$message?.success('删除成功!');
    getTableData();
  }
}

// 分页
const pagination: PaginationProps = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 15, 20, 25, 30],
  onChange: (page: number) => {
    pagination.page = page;
    getTableData();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    getTableData();
  },
});

const tableData = ref<any>([]);
async function getTableData() {
  startLoading();
  let params = {
    page: pagination.page,
    page_size: pagination.pageSize,
    keywords: keywords.value
  };
  const { data } = await selectOperatorLinksList(params);
  if (data) {
    tableData.value = data.item;
    pagination.itemCount = data.total;
    endLoading();
  }
}

function init() {
  getTableData();
}

// 初始化
init();
</script>

<style scoped></style>
